package com.yuzhihao.writejvm.attributes;

import com.yuzhihao.writejvm.clazz.ClassInfo;
import com.yuzhihao.writejvm.constant.ConstantUtf8Info;
import com.yuzhihao.writejvm.format.PrintFormat;
import com.yuzhihao.writejvm.read.Parse;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.log4j.Log4j2;

import java.awt.print.Printable;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.Objects;

/**
 * There may be at most one SourceFile attribute in the attributes table of a ClassFile structure.
 * <a href="https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.7.10">SourceFileAttribute</a>
 *
 * @author yzh
 * @since 2021年12月11日11:46:28
 */
@Data
@Log4j2
@EqualsAndHashCode(callSuper = true)
public class SourceFileAttribute extends Attributes {

    private int sourcefile_index_u2 = 2;

    private int sourcefile_index;

    private String constant;

    public SourceFileAttribute(String name){
        super();
        super.setAttribute_name(name);
    }

    @Override
    public void parse(DataInputStream dis, ClassInfo ci) {
        this.setCi(ci);
        try {
            super.attribute_length = Parse.byteToInt(super.attribute_length_u4, dis);
            this.sourcefile_index = Parse.byteToInt(this.sourcefile_index_u2, dis);
        } catch (IOException e) {
            log.error(e);
        }
    }

    public String getConstant() {
        if(Objects.nonNull(this.constant)){
            return this.constant;
        }

        ConstantUtf8Info cui = (ConstantUtf8Info)this.getCi().getCp_info().getPools().get(String.valueOf(sourcefile_index));
        this.constant = cui.getConstant();

        return constant;
    }

    @Override
    public String print(String print) {
        return "SourceFile" + PrintFormat.COLON+PrintFormat.EMPTY+this.getConstant()+System.lineSeparator();
    }
}
